﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;

namespace Common
{
   public class Request
    {
        /// <summary>
        /// Post数据到网站
        /// </summary>
        /// <param name="posturl">网址</param>
        /// <param name="postData">参数</param>
        /// <param name="ContentType"></param>
        /// <returns></returns>
        public static string RequestContents(string posturl,string method, string postData, string ContentType)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = System.Text.Encoding.GetEncoding("UTF-8");
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;

                request.Method = method;
                if (string.IsNullOrEmpty(ContentType))
                    request.ContentType = "application/x-www-form-urlencoded";
                else
                    request.ContentType = ContentType;
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

        #region RequestContents
        public static string RequestContents(string URL, string ContentType, string strMethod = "", string postData = "", string Authorization = "")
        {
            string strResult = "";

            try
            {
                HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);

                myHttpWebRequest.Timeout = 60000;
                myHttpWebRequest.Method = strMethod == "" ? "GET" : strMethod.ToUpper();
                myHttpWebRequest.ServicePoint.Expect100Continue = false;

                if (strMethod == "POST")
                    myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                else
                    myHttpWebRequest.ContentType = ContentType;
                if (!string.IsNullOrWhiteSpace(Authorization))
                    myHttpWebRequest.Headers.Add("Authorization", Authorization); //Bearer ya29.AHES6ZRZWHl5EiWJPM1Vwq__5pXR1kzYmI5adL_MF-tIbtFZ

                if (postData != "")
                {
                    byte[] byteData = Encoding.UTF8.GetBytes(postData); //Encoding.Default
                    myHttpWebRequest.ContentLength = postData.Length;
                    if (string.IsNullOrWhiteSpace(myHttpWebRequest.ContentType))
                        myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";
                    Stream stream = myHttpWebRequest.GetRequestStream();
                    stream.Write(byteData, 0, byteData.Length);
                    stream.Close();
                }

                myHttpWebRequest.AllowAutoRedirect = true;
                HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
                Stream receiveStream = myHttpWebResponse.GetResponseStream();
                System.Text.Encoding encode = System.Text.Encoding.UTF8;
                StreamReader readStream = new StreamReader(receiveStream, encode);
                strResult = readStream.ReadToEnd();
                readStream.Close();
                myHttpWebResponse.Close();
            }
            catch (WebException ex)
            {
                if (ex.Response != null)
                {
                   // Log.WriteLog("RequestContents:WebException:Message:" + ex.Message, "error");

                    foreach (string hdr in ex.Response.Headers)
                    {
                        if (hdr.ToLower() == "www-authenticate")
                        {
                            strResult = ex.Response.Headers[hdr];
                            break;
                        }
                    }

                    try
                    {
                        if (strResult == "" && ex.Response.ContentLength != 0)
                        {
                            using (Stream stream = ex.Response.GetResponseStream())
                            {
                                System.Text.Encoding encode = System.Text.Encoding.UTF8;
                                using (StreamReader reader = new StreamReader(stream, encode))
                                {
                                    strResult = reader.ReadToEnd();
                                }
                            }
                        }
                    }
                    catch { }
                }
            }
            catch (Exception ex)
            {
               // Log.WriteLog(ex.Message, "error");
            }

            return strResult;
        }
        #endregion
    }
}
